<template>
  <div class="personal-info-container">
    <!-- 个人数据区域 -->
    <div class="personal-data">
      <h2 class="title">个人数据</h2>
      <div class="data-box">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="data-item">
              <span class="label">用户名：</span>
              <span class="value">{{ user.user_name }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="data-item">
              <span class="label">名称：</span>
              <span class="value">{{ user.nick_name }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="data-item">
              <span class="label">身份：</span>
              <span class="value">{{ descriIdentity[user.role_name] }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="data-item">
              <span class="label">邮箱：</span>
              <span class="value">{{ user.user_email }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="data-item">
              <span class="label">电话：</span>
              <span class="value">{{ user.user_phone }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="data-item">
              <span class="label">地址：</span>
              <span class="value">{{ user.user_address }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 订单记录区域 -->
    <div class="order-data">
      <h2 class="title">订单记录</h2>
      <div class="order-table" v-loading="loading" element-loading-text="加载中...">
        <el-table :data="paginatedTableData" style="width: 100%" :border="true">
          <el-table-column prop="orderID" width="80" label="订单ID" />
          <el-table-column prop="counterParty" width="180" label="交易方" />
          <el-table-column prop="productID" width="80" label="产品ID" />
          <el-table-column prop="productName" width="180" label="产品名称" />
          <el-table-column prop="productCategory" width="90" label="产品类别" />
          <el-table-column prop="quantity" label="数量" />
          <el-table-column prop="unitPrice" label="单价" />
          <el-table-column prop="orderType" width="160" label="订单类型(我的行为)" />
          <el-table-column prop="time" width="150" label="时间" />
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:currentPage="currentPage"
            :page-size="pageSize"
            :page-sizes="[5, 10, 20]"
            :background="true"
            layout="prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElTable, ElTableColumn, ElPagination, ElRow, ElCol, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';
import { useMainStore } from '@/stores';
import { inject } from 'vue';

const router = useRouter();
const mainStore = useMainStore();
const $axios = inject('$axios');
const $tools = inject('$tools');
const descriIdentity = {"dealer":"经销商", "farmer":"农户", "gov":"政府"}
// 响应式变量
const user = ref({
  user_name: '',
  user_email: '',
  role_name: '',
  user_phone: '',
  user_address: ''
});

// 订单数据
const allOrders = ref([]);
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const loading = ref(false);

// 计算分页后的数据
const paginatedTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return allOrders.value.slice(start, end);
});

// 从 mainStore 中读取用户数据
onMounted(() => {
  const userData = mainStore.userdata;
  if (userData) {
    user.value = userData;
    fetchOrderData();
  } else {
    $tools.alertMsg('用户数据未找到，请重新登录', 'error');
    router.push('/login');
  }
});

// 获取订单数据
// 获取订单数据
async function fetchOrderData() {
  loading.value = true;
  try {
    const response = await $axios.get('/orders');
    console.log(response)
    if (response.data.code === 200) {
      allOrders.value = response.data.data.map(order => {
        const date = new Date(order.order_created_at);
        const formattedTime = `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}-${String(date.getUTCDate()).padStart(2, '0')} ${String(date.getUTCHours()).padStart(2, '0')}:${String(date.getUTCMinutes()).padStart(2, '0')}`;

        //const formattedTime = new Date(order.order_created_at).toLocaleString();
        return {
          orderID: order.order_id,
          productID: order.product_id,
          productName: order.product_name,
          productCategory: order.category,
          quantity: order.quantity,
          unitPrice: order.price,
          orderType: order.type,
          counterParty: order.counterparty,
          time: formattedTime
        };
      });
      total.value = allOrders.value.length;
    } else {
      $tools.alertMsg(response.data.msg || '获取订单数据失败', 'error');
    }
  } catch (error) {
    console.error('获取订单数据错误:', error);
    $tools.alertMsg('获取订单数据失败，请稍后重试', 'error');
  } finally {
    // 重置loading状态
    loading.value = false;
  }
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置当前页码
};

// 处理当前页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
};
</script>

<style scoped>
.personal-info-container {
  /* padding: 20px; */
  font-family: Arial, sans-serif;
}

.title {
  color: #319A19;
  margin-bottom: 20px;
}

.data-box {
  border: 1px solid #DCDFE6;
  padding: 20px;
  border-radius: 5px;
  margin-bottom: 20px;
}

.data-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.label {
  font-weight: bold;
  margin-right: 10px;
  width: 100px;
  display: inline-block;
}

.value {
  flex: 1;
}

.order-table {
  border: 1px solid #DCDFE6;
  padding: 20px;
  border-radius: 5px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.personal-data,
.order-data {
  margin-bottom: 30px;
}

.data-box {
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.el-table {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>